<template>
    <div id="app" class="complaint">
        <scroll-fixed>
            <page-bar>
                <div slot="middle" class="page-title">反馈</div>
                <i slot="right"></i>
            </page-bar>
        </scroll-fixed>
          <transition name="page-slide" mode="out-in">
            <div v-if="!isDone" key="edit">
                <div class="edit-box">
                    <textarea class="editor" v-model.trim="form.content"  @input="wordCut" placeholder="请写下您的意见或建议"></textarea>
                    <div class="uploader-list">
                        <div class="item" v-for="(img,index) in form.imgs" :key="index"  @click="previewImage(index)" :style="{'background-image':'url('+img+')'}">
                            <a href="javascript:void(0);" class="close" @click.self.stop="removeImage(index)"></a>
                        </div>
                    </div>
                    <div class="tool-bar">
                        <div class="tools">
                            <span id="filePicker">
                                <i class="uicon uicon-photo"></i>
                            </span>
                        </div>

                        <span class="count"><label>{{form.content.length}}</label>/{{max}}</span>
                    </div>
                </div>

                <a href="javascript:;" class="submit" :class="{'disabled': !formStatus || posting}" @click="submit">{{posting ? '正在提交' : '提交'}}</a>
            </div>
            <div class="report-done" v-else key="save">
                <i class="uicon uicon-report-done"></i>
                <p class="tit">你的投诉已提交</p>
                <p>感谢你的反馈，我们会在24小时内完成审核，</p>
                <p>并通过系统消息告诉你结果。</p>
                <p>你可以在我的页卡，<a href="javascript:;" @click="toMsgCenter">消息中心</a>查看</p>

                <a href="javascript:history.back();" class="done">确定</a>
            </div>
          </transition>
        <ui-preview :config="preview" v-if="preview.status" @close="preview.status = false" @remove="removeImage" />
    </div>
</template>

<script>
import pageBar from '../components/pagebar.vue'
import scrollFixed from '../components/scrollFixed.vue'
import uiPreview from '../components/preview.vue'

//获取选中的文本
function getSelectText(editor) {
    if (!editor) return; editor.focus();
    if (editor.document && editor.document.selection)
        return editor.document.selection.createRange().text;
    else if ("selectionStart" in editor)
        return editor.value.substring(editor.selectionStart, editor.selectionEnd);
}


export default {
  name: "feedback",
  components:{
    [pageBar.name]:pageBar,
    [scrollFixed.name]:scrollFixed,
    [uiPreview.name]:uiPreview,
  },
  data(){
      return {
          posting:false,
          max:200,
          isDone:false,
          preview:{
              status:false,
              active:0,
              list:[]
          },
          form:{
              content:'',
              filenames:[],
              imgs:[]
          }
      }
  },
  computed:{
      formStatus(){
          return this.form.content.length > 0 && this.form.content.length <=200;
      }
  },
  mounted(){
       // 修改头像
        window.upload = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // 文件接收服务端。
            server: this.$config.api + '?ct=upload&ac=index',
            pick: '#filePicker',
            // 只允许选择图片文件。
            accept: {
                capture:'',
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            chunked: true,                          
            chunkSize: 1*1024*1024,
            formData: {
                'file'  : 'file',
                "_token": localStorage.getItem("token"),
            }
        });

        upload.on('beforeFileQueued',  ( file ) =>{
            file.guid = WebUploader.Base.guid();
        });

        upload.on('uploadBeforeSend', (object, data, headers) => {
            headers["X-Requested-With"] = "XMLHttpRequest"
            data.guid = object.file.guid;
        });

        // 上传成功
        upload.on( 'uploadSuccess', ( file,response ) => {
            var res = JSON.parse(response._raw);
            this.form.filenames.push(res.data.filename);
        })
        
        function removeInputCapture(){
            let pick = document.querySelector('#filePicker input[type=file]');
            if(!pick){
                setTimeout(()=>{
                    removeInputCapture();
                },300)
                return false;
            }

            pick.removeAttribute('capture');
        }
        removeInputCapture();
        // 当有文件被添加进队列的时候
        upload.on( 'fileQueued', ( file )=>{
            upload.makeThumb(file,(error,src)=>{
                if(error){
                    this.$toast(error);
                }else{
                    this.form.imgs.push(src);
                }
            },1,1)
        });


  },
  methods:{
     previewImage(idx){
         this.preview.active = idx;
         this.preview.list = this.form.imgs.concat();
         this.preview.status = true;
     },
     wordCut(e){
            var len = e.target.value.length - getSelectText(e.target).length;
            var num = this.max;
            if (len > num && e.keyCode !== 8) {
                e.preventDefault();
                e.stopPropagation();
                e.target.value = e.target.value.substr(0, num);
                this.form.content =  e.target.value;
                return false;
            }
     },   
      submit(){
          if(!this.formStatus || this.posting) return false;
          this.postDate();
      },
      postDate(){
          this.posting = true;
          this.$http.post('?ct=member_center&ac=add_feedback',{img:this.form.filenames,content:this.form.content})
            .then(response=>{
                let {data} = response;
                if(data.code == 0){
                     this.isDone = true;
                     this.form.imgs = [];
                     this.form.filenames = [];
                     this.form.content = [];
                     this.$toast('反馈成功');
                     this.isDone = true;
                 }else{
                     this.$toast(data.msg);
                 }
            }).catch(e=>{
                 window.$zEvent.$emit('ERROR',e);
                 this.$toast(e);
             }).finally(()=>{
                this.posting = false;
             })
      },
      removeImage(idx){
          this.form.imgs.splice(idx,1);
          this.form.filenames.splice(idx,1);
          //清除webuploader队列
          upload.removeFile(upload.getFiles()[idx],true);
      }
  }
};
</script>

<style lang="less">
.complaint {
    .page-title {
        color:#282828;
        font-size:36px;
    }
  .edit-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    height: 481px;
    margin-top: 20px;
    background-color: #fff;
    .editor {
      flex:1;
      padding: 30px;
      width: 100%;
      font-size: 34px;
      color: #282828;
      line-height: 52px;
      outline: none;
      border:none;
      &::-webkit-input-placeholder {
          font-size:28px;
          color:#c6c6c6;
      }
    }
    .uploader-list {
      width:100%;
      display: flex;
      flex-wrap: wrap;
      .item {
        flex-grow: 0;
        flex-shrink: 0;
        background-color: #f5f5f5;
        position: relative;
        margin-left: 20px;
        width: 150px;
        height: 150px;
        border-radius:10px;
        background-repeat: no-repeat;
        background-position: top center; 

        .close {
            position:absolute;
            top:-6px;
            right:-6px;
            width:28px;
            height:28px;
            border-radius:50%;
            background-color:#e64a19;

            &::after,
            &::before {
                content: '';
                position: absolute;
                top:50%;
                left:50%;
                transform: translate(-50%,-50%) rotate(45deg);
                background-color:#fff;
                border-radius: 10px;
            }
            
            &:before {
                width:14px;
                height:2px;
            }

            &::after {
                width:2px;
                height:14px;
            }
        }
      }
    }

    .tool-bar {
      width:100%;
      padding: 30px;
      display: flex;
      justify-content: space-between;
      align-items: cetner;
      font-size: 24px;
      color: #c6c6c6;

      label {
        color: #282828;
      }
    }
  }
  .submit,.done {
    margin: 50px 30px 0;
    display: block;
    text-align: center;
    line-height: 88px;
    height: 88px;
    font-size: 36px;
    color: #fff;
    border-radius: 8px;
    background-color: #e64a19;

    &.disabled {
      opacity: 0.6;
    }
  }

  #filePicker {
      overflow: hidden;
      input {
          opacity:0;
      }
  }
  .report-done {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding:158px 30px 30px;

        .tit {
            margin-top:66px;
            margin-bottom:30px;
            font-size:36px;
            color:#282828;
        }
        p {
            margin-bottom:20px;
            line-height: 1;
            font-size:32px;
            color:#666;

            a {
                color:#e64a19;
            }
        }
        .done {
            margin-top:70px;
            width:100%;
        }
    }
}
</style>

